package controllers

import (
	"encoding/json"
	"errors"
	"odooapp/app/odooapi"

	"github.com/revel/revel"
)

type App struct {
	*revel.Controller
}

func (c App) Index() revel.Result {
	return c.Render()
}

func GetAliveOdooClient(c *revel.Params) (*odooapi.Client, map[string]interface{}, error) {
	var jsonData map[string]interface{}
	c.BindJSON(&jsonData)
	sessionId, okSid := jsonData["session_id"]

	// urlStr can read locallly
	// urlParam, okUrl := jsonData["url"]
	authJson, okAuth := jsonData["jsonAuth"]
	var auth = odooapi.AuthResponse{}
	if !(okSid && okAuth) {
		return nil, jsonData, errors.New("Auth token missed.")
	}

	err := json.Unmarshal([]byte(authJson.(string)), &auth)
	if err != nil {
		return nil, jsonData, errors.New("Error to convert json to struct.")
	}

	client, err := odooapi.BuildOdooClient(string(auth.Result.WebBaseURL), sessionId.(string), &auth)
	if err != nil {
		return nil, jsonData, err
	}
	return client, jsonData, nil
}
